package com.project_doctor.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project_doctor.pojo.Conversation;
import com.project_doctor.pojo.Message;
import com.project_doctor.service.ConversationService;
import com.project_doctor.service.MessageService;
import com.project_doctor.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* @author 龙龙与贝儿
* @description 针对表【t_message】的数据库操作Service实现
* @createDate 2025-06-07 11:22:51
*/
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
    implements MessageService{
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    @Lazy
    ConversationService conversationService;

    @Override
    @Transactional
    public Message saveMessage(Message message) {
        message.setMessageTime(new Date());
        message.setIsRead(0);
        messageMapper.insert(message);
        // 手动查询完整记录（需要根据实际情况调整查询条件）
        message = messageMapper.selectById(message.getId());
        // 更新对话的最新消息
        Conversation conversation = conversationService.getConversationById(message.getConversationId());
        conversation.setUnreadCount(conversation.getUnreadCount() + 1);
        conversation.setLatestMessageId(message.getId());
        conversation.setLatestMessage(message);
        conversationService.updateConversation(conversation);

        return message;
    }

    @Override
    public List<Message> getMessagesByConversationId(Long conversationId) {
        List<Message> messages = messageMapper.getMessagesByConversationId(conversationId);
        return messages;
    }
}




